import time
from datetime import datetime
import os
import math
import operator
from functools import reduce
from PIL import ImageGrab
from apscheduler.schedulers.blocking import BlockingScheduler
import imagehash
config={
    "screenRange":[133,179,1788,1109], #截图的范围x1,y1,x2,y2
    "fileName":'C:/Users/DingMiaoBin/Desktop/资料/数字图像处理技术'
}

def get_screenshot():
    """截图
    """
    range=config["screenRange"]
    bbox = (range[0], range[1], range[2],range[3])
    im = ImageGrab.grab(bbox)
    return im
def compareTwoImage(image1,image2):
    # h1 = image1.histogram()
    # h2 = image2.histogram()
    # rms = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1))
    h1=imagehash.dhash(image1)
    h2=imagehash.dhash(image2)
    rms=math.fabs(h1-h2)

    return rms

def work():
    global  lastImage
    print("work")
    newImage=get_screenshot()
    print(lastImage)
    print(newImage)
    num=compareTwoImage(lastImage,newImage)
    print(num)
    if num>0:
        newImage.save(config["fileName"]+"/"+str(int(time.time()))+".png")
    lastImage=newImage
if __name__ == '__main__':
    global lastImage
    print("程序启动")
    scheduler = BlockingScheduler()
    scheduler.add_job(func=work, trigger= 'interval', seconds=1)
    print("定时任务注册完毕")
    print("开始初始化图片")
    lastImage=get_screenshot()
    scheduler.start()
